<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>TTS页面</title>
  </head>
  <body>
    <h1>TTS页面</h1>

    <label for="text">合成内容：</label>
    <input type="text" id="text" placeholder="输入要合成的内容" />

    <label for="voice">音色：</label>
    <select id="voice">
      <option value="aisbabyxu">音色1</option>
      <option value="voice2">音色2</option>
      <option value="voice3">音色3</option>
      <!-- 添加更多音色选项 -->
    </select>

    <button id="submitBtn">合成并播放</button>

    <script>
      document
        .getElementById('submitBtn')
        .addEventListener('click', function () {
          var text = document.getElementById('text').value;
          var voice = document.getElementById('voice').value;

          var audioContext = new (window.AudioContext ||
            window.webkitAudioContext)();
          var mediaSource = new MediaSource();
          var audioElement = document.createElement('audio');
          audioElement.src = URL.createObjectURL(mediaSource);
          document.body.appendChild(audioElement);

          var sourceBuffer = null;
          var isPlaying = false;
          var startTime = 0;

          mediaSource.addEventListener('sourceopen', function () {
            sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');
          });

          var socket = new WebSocket('ws://192.168.2.127:9002/jhl/tts');

          socket.onopen = function () {
            console.log('连接已建立');
            var message = {
              text: text,
              voice: voice,
            };
            socket.send(JSON.stringify(message));
          };

          socket.onmessage = function (event) {
            var audioData = event.data;
            console.log(audioData, 'audioData');
            if (sourceBuffer && !isPlaying) {
              var reader = new FileReader();
              reader.onload = function () {
                var arrayBuffer = reader.result;

                sourceBuffer.appendBuffer(arrayBuffer);
                if (!isPlaying) {
                  audioElement.play();
                  isPlaying = true;
                }
              };
              reader.readAsArrayBuffer(audioData);
            }
          };

          socket.onclose = function (event) {
            console.log('连接已关闭');
          };
        });
    </script>
  </body>
</html>
